#!/usr/bin/python
# -*- coding: utf-8 -*-

# --------------------------------------------------------------------------- #
#                                                                             #
#    Plugin for iSida Jabber Bot                                              #
#    Copyright (C) 2012 diSabler <dsy@dsy.name>                               #
#    Copyright (C) 2012 Vit@liy <vitaliy@root.ua>                             #
#                                                                             #
#    This program is free software: you can redistribute it and/or modify     #
#    it under the terms of the GNU General Public License as published by     #
#    the Free Software Foundation, either version 3 of the License, or        #
#    (at your option) any later version.                                      #
#                                                                             #
#    This program is distributed in the hope that it will be useful,          #
#    but WITHOUT ANY WARRANTY; without even the implied warranty of           #
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the            #
#    GNU General Public License for more details.                             #
#                                                                             #
#    You should have received a copy of the GNU General Public License        #
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.    #
#                                                                             #
# --------------------------------------------------------------------------- #

# transsdflate: chat_log,away_log,xa_log,dnd_log

import re
import urllib2
from xml.dom.minidom import parseString
import random
import time
import sys
from translit import translify

gelbooru_get_count = 'http://gelbooru.com/index.php?page=dapi&s=post&q=index&tags=%s&limit=0'
gelbooru_get_post = 'http://gelbooru.com/index.php?page=dapi&s=post&q=index&tags=%s&pid=%d&limit=%s'
gelbooru_post_page = 'http://gelbooru.com/index.php?page=post&s=view&id=%s'

def run_query(*params):
	cur = conn.cursor()
	if base_type == 'pgsql': psycopg2.extensions.register_type(psycopg2.extensions.UNICODE, cur)
	try:
		cur.execute(*params)
		rslt = cur.fetchall()
		cur.close()
		return rslt
	except:
		conn.rollback()
		raise

class TaskManager:
	last_cmd_time = 0
	# sender is a dict {room, nick, type}
	def perform_command(self, sender, query):
		try:
			print str(time.time()) + ' - ' + str(self.last_cmd_time)
			if time.time() - self.last_cmd_time < 5:
				exit
			self.last_cmd_time = time.time()
			translited = translify(query).replace("'", "")
			print 'Transliterated query: ' + translited
			rslt = run_query('''
	select name, orig_name, similarity(%s, name) + log(count)/20 as sim from
	tmptags
	 where type = 'character' order by sim desc limit 5;
			''',(translited,))
			if not rslt:
				send_msg(sender['type'], sender['room'], sender['nick'], u'Няшка протерялась')
				exit

			tag = rslt[0][1]
			print u'Search result ' + unicode(rslt)
			print u'Tag ' + tag
			response = urllib2.urlopen(gelbooru_get_count % tag)
			xml = response.read()
			print xml
			xml = parseString(xml)
			count = int(xml.getElementsByTagName('posts')[0].getAttribute('count'))
			limit = 30
			if count / 30 < 1:
				index = 0
			else:
				index = random.randrange(0, count / 30)
			print "Posts count %d, selected index %d * 10" % (count, index)
			response = urllib2.urlopen(gelbooru_get_post % (tag, index, limit))
			xml = response.read()
			#print xml
			xml = parseString(xml)
			max_score = -1
			fav_post = None
			for post in xml.getElementsByTagName('post'):
				score = int(post.getAttribute('score'))
				rating = post.getAttribute('rating')
				if (rating == 'q' or rating == 's') and score > max_score:
					max_score = score
					fav_post = post
			if not fav_post:
				raise Exception('Failed to get the best scored post')
			element = fav_post
			#print element.toxml()
			file_url = element.getAttribute('file_url')
			tags = element.getAttribute('tags')
			id = element.getAttribute('id')
#			send_msg(u'groupchat', room, user, tags + '\n' + file_url + '\n' + 
#			  gelbooru_post_page % (id))
			send_msg(sender['type'], sender['room'], sender['nick'], tag + '\n' + file_url)
		except Exception, e:
			send_msg(sender['type'], sender['room'], sender['nick'], u'Ошибка %s: %s' % (e.__class__.__name__, e.message))
		  
task_manager = TaskManager()

bot_command_match = u'\S*пост\S*';
bot_command_name = u'(qb|к.?[ую]б)\S*';

from traceback import print_stack

def test_msg_for_request_token(room,jid,nick,mtype,text):
	splitted_text = text.split()
	words = u' '.join(splitted_text[:1]).lower()
	query = u' '.join(splitted_text[1:]).lower()
	print words
#	print repr((room, jid, nick, type, text))
	if re.search(bot_command_name, words) and re.search(bot_command_match, query.lower()):
		query = re.sub(bot_command_match, u'', query)
		query = re.sub(u'(мне|нам|им|ему|ей)', u'', query)
		print repr(query)
		print u'get query: ' + query
#		print u' ' + repr((u'groupchat', room, nick, text))
		#send_msg(u'groupchat', room, nick, u'ты писал мне ' + text)
		task_manager.perform_command({'room': room, 'nick': nick, 'type': mtype}, query.strip())

message_control = [test_msg_for_request_token]
